# -*- coding: utf-8 -*-
# standard
import os
import sys

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from functions import *


"""
@Title:   
@File: 优化数据库查询的尝试.py
@Author: walle 2025年07月20日 07时54分03秒
@Version: 1.0.0
@Desc: 
"""


def query_strategy(customer_id: int = 107, store_id: int = 451, db_session: Session | None = None) -> float:
    """
    查询策略
    """
    db_session, need_close = (new_db_session(sync=True), True) if db_session is None else (db_session, False)
    b1 = time.perf_counter()
    source = NotificationSource.GATEWAY_OFFLINE
    conditions = [
        NotificationStrategyOrm.customer_id == customer_id,
        NotificationStrategyOrm.is_enabled == 1,      
        NotificationStrategyOrm.is_deleted == 0, 
        NotificationStrategyOrm.cond.has(NotificationConditionOrm.sources.any(source.value, operator=operators.eq)),
        or_(
            NotificationStrategyOrm.cond.has(NotificationConditionOrm.store_ids.any(store_id, operator=operators.eq)),
            NotificationStrategyOrm.cond.has(NotificationConditionOrm.store_ids == []),
        )
    ]
    s = select(NotificationStrategyOrm).where(
        *conditions
    ).options(
        joinedload(NotificationStrategyOrm.methods),
    )
    strategies = db_session.scalars(s).unique().all()
    b2 = time.perf_counter()
    d = (b2 - b1) * 1000
    logger.debug(f"cost: {d:.2f} ms")
    print(strategies)
    if need_close:
        db_session.close()
    return d 


def main1(n: int = 20):
    """
    测试策略查询性能
    :param n: _description_, defaults to 20
    """
    customer_id, store_id = 107, 451
    db_session = new_db_session(sync=True)
    times = []
    for i in range(n):
        d = query_strategy(customer_id, store_id, db_session)
        times.append(d)
    times.sort()
    logger.debug(f"最大耗时: {times[-1]:.2f} ms")
    logger.debug(f"最小耗时: {times[0]:.2f} ms")
    logger.debug(f"平均耗时: {sum(times) / n:.2f} ms")
    logger.debug(f"去掉最大最小奇异值的平均耗时: {sum(times[1:-1]) / (n - 2):.2f} ms")
    db_session.close()
    


if __name__ == '__main__':
    pass